package com.cube.share.async.config;

import com.cube.share.async.executor.AsyncExecutor;
import com.cube.share.async.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author cube.li
 * @date 2022/2/19 14:35
 * <p>
 * 异步服务自动配置类
 */
@Configuration
@EnableConfigurationProperties(AsyncThreadPoolProperties.class)
@Slf4j
public class AsyncExecutorAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "iAsyncExecutor")
    public ThreadPoolExecutor iAsyncExecutor(AsyncThreadPoolProperties poolProperties) throws InstantiationException, IllegalAccessException {
        log.info("加载iAsyncExecutor...");
        ThreadFactoryBuilder threadFactoryBuilder = ThreadFactoryBuilder.create()
                .setNamePrefix(poolProperties.getThreadNamePrefix())
                .setPriority(poolProperties.getPriority());
        Class<? extends RejectedExecutionHandler> rejectedExecutionHandlerType = poolProperties.getRejectedExecutionHandlerType();
        RejectedExecutionHandler rejectedExecutionHandler;
        if (rejectedExecutionHandlerType == null || rejectedExecutionHandlerType.isInterface()) {
            rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
        } else {
            rejectedExecutionHandler = rejectedExecutionHandlerType.newInstance();
        }
        return new ThreadPoolExecutor(poolProperties.getCorePoolSize(),
                poolProperties.getMaximumPoolSize(),
                poolProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(30), threadFactoryBuilder.build(),
                rejectedExecutionHandler);
    }

    @Bean
    @ConditionalOnBean(name = "iAsyncExecutor")
    public AsyncExecutor asyncExecutor(@Qualifier("iAsyncExecutor") @Autowired ThreadPoolExecutor iAsyncExecutor) {
        AsyncExecutor asyncExecutor = new AsyncExecutor();
        asyncExecutor.setExecutor(iAsyncExecutor);
        return asyncExecutor;
    }

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        log.info("加载spring task thread pool...");
        ThreadPoolTaskExecutor bean = new ThreadPoolTaskExecutor();
        bean.setMaxPoolSize(16);
        bean.setCorePoolSize(10);
        bean.setKeepAliveSeconds(30);
        bean.setQueueCapacity(50);
        bean.setThreadNamePrefix("spring-task-thread-");
        bean.setThreadGroupName("spring-task");
        return bean;
    }

}
